package com.intel.bluetooth;

import com.intel.surface.UnconnectDevicePn;
import lombok.Data;

import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

@Data
public class ConnectService extends Thread {
    private StreamConnection clientSession;
    private DataInputStream dataInputStream;
    private DataOutputStream dataOutputStream;
    private SocketService socketService;
    private Boolean connecting;
    private byte[] recvBuf = new byte[1024];
    private long mostWaitTime = 5 * 1000;

    private UnconnectDevicePn unconnectDevicePn;
    private DeviceConnectService deviceConnectService;
    private String address;

    public ConnectService(UnconnectDevicePn unconnectDevicePn, DeviceConnectService deviceConnectService) {
        this.unconnectDevicePn = unconnectDevicePn;
        this.deviceConnectService = deviceConnectService;
        this.address = deviceConnectService.getRemoteDevice().getBluetoothAddress().toUpperCase();
    }

    @Override
    public void run() {
        connecting = true;
        String serverURL = "btspp://" + address + ":1;authenticate=false;encrypt=false;master=false";
        try {
            clientSession = (StreamConnection) Connector.open(serverURL);
            dataInputStream = clientSession.openDataInputStream();
            dataOutputStream = clientSession.openDataOutputStream();
        } catch (IOException e) {
            System.err.println("连接蓝牙设备失败");
            e.printStackTrace();
            return;
        }

        socketService = new SocketService();
        boolean success = socketService.connectServer(ConnectService.this);
        if (!success) {
            System.err.println("连接服务器失败");
            return;
        }
        socketService.start();
        deviceConnectService.setRun(true);
        unconnectDevicePn.getFrame().connectSuccess(unconnectDevicePn, ConnectService.this);

        int temp = 0;
        while (connecting) {
            try {
                if (dataInputStream.available() <= 0) {
                    temp += 10;
                    if (temp >= mostWaitTime) {
                        System.err.println("接收数据超时，重新连接设备");
                        closeConnection(true);
                    }
                } else {
                    temp = 0;
                    System.out.println(recvBuf);
                    int length = dataInputStream.read(recvBuf);
                    socketService.sendBytes(recvBuf, length);
                }

                Thread.sleep(10);
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void sendToDevice(byte[] bytes, int len) {
        if (dataOutputStream != null) {
            try {
                dataOutputStream.write(bytes, 0, len);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void closeConnection(boolean reconnect) {
        socketService.close();
        try {
            connecting = false;
            dataInputStream.close();
            dataOutputStream.close();
            clientSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!reconnect)
            deviceConnectService.setGoing(false);
        deviceConnectService.setRun(reconnect ? false : true);
    }
}
